//global variables
var seconds;
var bugs;
var game_on=false;
var paused; //when true, allows no other action to be performed
var timerID;
var spot=new Array(rows);
var showing=new Array(rows*cols); //true if the "blank.gif" isn't showing
var num_showing; //number of elements which are set to true in showing array
var num_revealed; //number of spots revealed or marked
var player;
var max_time=999;
var no_left_click; //used to start timer after the first left-click of the new game
var search_list=new Array();
var search_list_size=0;

function page_load() {
  player=prompt('Please enter your name for the record:','Anonymous');
  if(player=="" || player==null)
    player="Anonymous";
  if(document.cookie=="" || document.cookie.indexOf(player+"_expert_time")==-1)
    default_scores();
  document.info.reset();
  document.info.runner.value='New Game';
}

function shortcuts_menu() {
  helpWin=window.open("shortcuts.html");
}

function default_scores() {
  //function used to reset scores to default value
  Delete_Cookie(player+"_beginner_time");
  Delete_Cookie(player+"_intermediate_time");
  Delete_Cookie(player+"_expert_time");
  var today = new Date();
  var expires_date = new Date(today.getTime() + (52 * 7 * 86400000));
  fixDate(expires_date);
  if(Get_Cookie(player+"_beginner_time")==null)
    Set_Cookie(player+"_beginner_time",max_time,expires_date);
  if(Get_Cookie(player+"_intermediate_time")==null)
    Set_Cookie(player+"_intermediate_time",max_time,expires_date);
  if(Get_Cookie(player+"_expert_time")==null)
    Set_Cookie(player+"_expert_time",max_time,expires_date);
}

function run() {
  if(game_on)
    stop_game();
  else
    new_game();
}

function new_game() {
  game_on=true;
  paused=false;
  for(var i=0;i<rows*cols;i++)
    if(showing[i]==true)
      document.images[i+pic_offset].src=img_dir+"/blank.gif";
  document.info.reset();
  set_game_vars();
  no_left_click=true;
  document.info.runner.value="Stop Game";
}

function stop_game() {
  game_on=false;
  clearInterval(timerID);
  reveal_all();
  document.info.runner.value="New Game";
  document.info.time.value="";
}

function timer() {
  if(seconds==max_time) {
    alert("Sorry. You've exceeded the time limit of "+max_time+" seconds.");
    stop_game();
  }
  if(game_on && !paused)
    document.info.time.value=++seconds;
}

function set_game_vars() {
  seconds=0;
  bugs=total_bugs;
  for(var i=0;i<rows;i++)
    spot[i]=new Array(cols);
  var choice=new Array(rows*cols);
  num_showing=0;
  num_revealed=0;
  for(var i=0;i<rows;i++)
    for(var j=0;j<cols;j++) {
      showing[i*cols+j]=false;
      choice[i*cols+j]=i*cols+j;
      spot[i][j]=0;
    }
  var size=choice.length;
  var r=new Array(total_bugs);
  var c=new Array(total_bugs);
  for(var i=0;i<total_bugs;i++) {
    var rnd=Math.floor(Math.random()*size--);
    //set spot to "bug" to indicate that the spot has a bug
    var row=Math.floor(choice[rnd]/cols);
    var col=choice[rnd]%cols;
    r[i]=row;
    c[i]=col;
    spot[row][col]="bug";

    //swap choice with last choice[size] so the spot won't be reused
    var temp=choice[rnd];
    choice[rnd]=choice[size];
    choice[size]=temp;
  }

  //evaluate numbers in spots that don't have bugs
  for(var i=0;i<total_bugs;i++) {
    var row=r[i];
    var col=c[i];
    for(var j=row-1;j<=row+1;j++)
      if(j>=0 && j<rows)
        for(var k=col-1;k<=col+1;k++)
          if(k>=0 && k<cols && spot[j][k]!="bug")
            spot[j][k]+=1;
  }
}

function left_click(r,c) {
  //operation code (this is the game play code, don't screw up here)
  if(!game_on) {
    alert("You haven't started the game, silly.");
    return; //no action if game hasn't started
  } else if(paused)
    return;
  else if(no_left_click) {
    no_left_click=false;
    timer();
    timerID=setInterval("timer()",1000);
  }
  paused=true;
  search_list[search_list_size++]=r*cols+c;
  while(search_list_size!=0) {
    var row=Math.floor(search_list[search_list_size-1]/cols);
    var col=search_list[--search_list_size]%cols;
    search(row,col);
  }
  if(num_revealed==rows*cols && bugs==0)
    winner();
  paused=false;
}

function right_click(event,row,col) {
  if(!game_on) {
    alert("You haven't started the game, silly.");
    return; //no action if game hasn't started
  } else if(paused)
    return false;
  var nav=navigator.appName;
  var IE="Microsoft Internet Explorer";
  var NS="Netscape";
  if ((nav==NS && event.which==3 && game_on) || (nav==IE && event.button==2 && game_on)) {
    paused=true;
    var img=document.images[row*cols+col+pic_offset];
    if(img.src==img_dir+"/blank.gif") {
      //convert blank spot to marked spot
      img.src=img_dir+"/mark.gif";
      showing[row*cols+col]=true;
      num_showing++;
      num_revealed++;
      document.info.bugs_left.value=--bugs;
    }
    else if(img.src==img_dir+"/mark.gif") {
      //convert marked spot to question mark
      img.src=img_dir+"/question.gif";
      num_revealed--;
      document.info.bugs_left.value=++bugs;
    }
    else if(img.src==img_dir+"/question.gif") {
      //convert question mark to blank spot
      img.src=img_dir+"/blank.gif";
      showing[row*cols+col]=false;
      num_showing--;
    } else if(spot[row][col]!=0) {
      search_area(row,col);
      while(search_list_size!=0) {
        var row=Math.floor(search_list[search_list_size-1]/cols);
        var col=search_list[--search_list_size]%cols;
        search(row,col);
      }
    }
    if(num_revealed==rows*cols && bugs==0)
      winner();
    paused=false;
    return false;
  }
  return true;
}

function winner() {
    //winning code here
    game_on=false;
    clearInterval(timerID);
    document.info.runner.value="New Game";
    alert("Congratulations "+player+"! You won in "+seconds+" seconds.\nYou've won a night in a roach-free hotel. That means that for the roaches, it's free.");
    //add cookie code here to save high score
    if(!custom_game) {
      var today = new Date();
      var expires_date = new Date(today.getTime() + (52 * 7 * 86400000));
      fixDate(expires_date);
      if(total_bugs==10 && seconds<Get_Cookie(player+"_beginner_time"))
        Set_Cookie(player+"_beginner_time",seconds,expires_date);
      else if(total_bugs==40 && seconds<Get_Cookie(player+"_intermediate_time"))
        Set_Cookie(player+"_intermediate_time",seconds,expires_date);
      else if(total_bugs==99 && seconds<Get_Cookie(player+"_expert_time"))
        Set_Cookie(player+"_expert_time",seconds,expires_date);
    }
}

function high_scores() {
  var msg="<HTML><HEAD><TITLE>High Scores for: "+player+"</TITLE></HEAD><BODY><CENTER>";
  msg+="<H2>High Scores for: "+player+"</H2><P>";
  msg+="Beginner: "+Get_Cookie(player+"_beginner_time")+" seconds<BR>";
  msg+="Intermediate: "+Get_Cookie(player+"_intermediate_time")+" seconds<BR>";
  msg+="Expert: "+Get_Cookie(player+"_expert_time")+" seconds<P><FORM>";
  msg+='<INPUT TYPE=BUTTON VALUE="Reset Scores" onClick="opener.default_scores();opener.high_scores();self.close();">';
  msg+='<INPUT TYPE=BUTTON VALUE="Close Window" onClick="self.close();">';
  msg+="</FORM></BODY></HTML>";
  var scoreWin=window.open("","","height=500,width=500");
  scoreWin.document.write(msg);
  scoreWin.document.close();
}

function help() {
  var helpWin=window.open("help.html","","width=800,height=600");
}

function search(row,col) {
  var img=document.images[row*cols+col+pic_offset];
  if(img.src==img_dir+"/blank.gif" || img.src==img_dir+"/question.gif") {
    if(spot[row][col]=="bug") {
      //losing code here
      img.src=img_dir+"/bug_clicked.gif";
      showing[row*cols+col]=true;
      stop_game();
      reveal_all();
      alert('Sorry pal. The bug bit you and you died.\nGame Over!');
      return;
    }
    img.src=img_dir+"/"+spot[row][col]+".gif";
    showing[row*cols+col]=true;
    num_showing++;
    num_revealed++;
    if(spot[row][col]==0)
      search_area(row,col);
  }
}

function search_area(row,col) {
  var count=0;
  var original_search_list_size=search_list_size;
  for(var j=row-1;j<=row+1;j++)
    if(j>=0 && j<rows)
      for(var k=col-1;k<=col+1;k++)
        if(k>=0 && k<cols && !(j==row && k==col))
          if(showing[j*cols+k]!=true) {
            //document.images[j*cols+k+pic_offset].src=img_dir
            search_list[search_list_size++]=j*cols+k;
          }
          else if(document.images[j*cols+k+pic_offset].src==img_dir+"/mark.gif")
            count++;
  if(count!=spot[row][col])
    search_list_size=original_search_list_size;
}

function reveal_all() {
  for(var i=0;i<rows;i++)
    for(var j=0;j<cols;j++)
      if(showing[i*cols+j]!=true && spot[i][j]=="bug") {
        document.images[i*cols+j+pic_offset].src=img_dir+"/bug.gif";
        showing[i*cols+j]=true;
      } else if(spot[i][j]!="bug" && document.images[i*cols+j+pic_offset].src==img_dir+"/mark.gif") {
        document.images[i*cols+j+pic_offset].src=img_dir+"/bad_mark.gif";
        showing[i*cols+j]=true;
      }
}

function nocontextmenu(event) {
  return false;
}
document.oncontextmenu = nocontextmenu;
